<%@ Page Language="C#" %>
<html>
<head runat="server">
  <title>Hello World IFrame Facebook Application</title>
  <link rel="stylesheet" type="text/css" href="Page.css" />
</head>
<body>
  <fb:FacebookApplication ID="fbApplication" runat="server" Mode="IFrame"
    EnableExternalBrowsing="true"
    ApplicationName="helloWorld" />
    
  <form runat="server">
    <h1>Hello World</h1>
    <h2><asp:Label runat="server" ID="greetingLabel" /></h2>
    
    <hr />
    
    <h2>How about saying Hello to your friends?</h2>
    <table cellpadding="4" cellspacing="0" border="0">
      <tr>
        <td>Select a greeting:</td>
        <td>
          <asp:DropDownList runat="server" ID="greetingDropDownList">
            <asp:ListItem Text="Hi!" Value="Hi" />
            <asp:ListItem Text="Hey!" Value="Hey" />
            <asp:ListItem Text="Hello!" Value="Hello" />
          </asp:DropDownList>
        </td>
      </tr>
      <tr runat="server" id="friendsRow">
        <td>Select some friends:</td>
        <td>
          <asp:ListBox runat="server" ID="friendList" SelectionMode="Multiple"
            DataSourceID="friendsQuery"
            DataTextField="name" DataValueField="uid" />
        </td>
      </tr>
      <tr runat="server" id="storyRow">
        <td>&nbsp;</td>
        <td><asp:CheckBox runat="server" ID="createStoryCheckBox" Text="Create mini-feed story" /></td>
      </tr>
      <tr>
        <td colspan="2"><hr /></td>
      </tr>
      <tr>
        <td colspan="2" align="right">
          <asp:Button runat="server" ID="sendGreetingButton" Text="Send Greeting" OnClick="OnSendGreetingClick" />
        </td>
      </tr>
    </table>
    
    <fb:FqlDataSource runat="server" ID="friendsQuery"
      FqlQuery="SELECT name, uid from user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=@UserID)">
      <Parameters>
        <asp:ControlParameter Name="UserID" ControlID="fbApplication" PropertyName="UserID" />
      </Parameters>
    </fb:FqlDataSource>
    
    <hr />
    
    <fb:FacebookHyperLink runat="server" id="photosLink" NavigateUrl="Photos.aspx" Text="Browse Photos" />
  </form>
  <script runat="server">
    
    private void Page_Load() {
        if (fbApplication.IsSessionCreated == false) {
            return;
        }

        if (fbApplication.Session.SessionType == Facebook.Service.Core.FacebookSessionType.User) {
            User user = fbApplication.Service.Users.GetUser(null, "name");
            if (user != null) {
                greetingLabel.Text = "Hello " + user.Name;
            }
        }
        else {
            PresencePage page = fbApplication.Service.Pages.GetPage(null);
            if (page != null) {
                greetingLabel.Text = "Hello, fans of " + page.Name;
            }

            friendsRow.Visible = false;
            storyRow.Visible = false;
        }

        if (!IsPostBack) {      
            UserPreferences preferences = fbApplication.Service.Preferences.LoadPreferences();
            if (preferences != null) {
                string greeting = preferences[0];
                if (String.IsNullOrEmpty(greeting) == false) {
                    foreach (ListItem listItem in greetingDropDownList.Items) {
                        if (listItem.Value == greeting) {
                            listItem.Selected = true;
                        }
                    }
                }
            }
        }
    }

    private string BuildProfileFbml(IList<string> ids, string greeting) {
        StringBuilder fbmlBuilder = new StringBuilder();

        if (fbApplication.Session.SessionType == Facebook.Service.Core.FacebookSessionType.User) {
            fbmlBuilder.Append("<div>");
            fbmlBuilder.Append("<fb:name capitalize=\"true\" uid=\"");
            fbmlBuilder.Append(fbApplication.Service.UserID);
            fbmlBuilder.Append("\" firstnameonly=\"true\" />");
            fbmlBuilder.Append(" said <b>");
            fbmlBuilder.Append(greeting);
            fbmlBuilder.Append("</b> to:");
            fbmlBuilder.Append("<fb:user-table>");

            for (int i = 0; i < ids.Count; i++) {
              fbmlBuilder.Append("<fb:user-item uid=\"");
              fbmlBuilder.Append(ids[i]);
              fbmlBuilder.Append("\" />");
            }

            fbmlBuilder.Append("</fb:user-table>");
            fbmlBuilder.Append("</div>");
            fbmlBuilder.Append("<div>Say <a href=\"http://apps.facebook.com/nikhilrandom\">Hello World</a>!</div>");
        }
        else {
            fbmlBuilder.Append("<div>");
            fbmlBuilder.Append("<fb:name capitalize=\"true\" uid=\"");
            fbmlBuilder.Append(fbApplication.Service.UserID);
            fbmlBuilder.Append("\" /> said <b>");
            fbmlBuilder.Append(greeting);
            fbmlBuilder.Append("</b> to all the fans.");
            fbmlBuilder.Append("</div>");
        }

        return fbmlBuilder.ToString();
    }

    private void OnSendGreetingClick(object sender, EventArgs e) {
        string greeting = greetingDropDownList.SelectedItem.Text;
        string profileFbml = null;

        FacebookService service = fbApplication.Service;

        if (fbApplication.Session.SessionType == Facebook.Service.Core.FacebookSessionType.User) {
            int[] selectedIndices = friendList.GetSelectedIndices();
            if (selectedIndices.Length != 0) {
                List<string> friends = new List<string>(selectedIndices.Length);
                foreach (int i in selectedIndices) {
                    friends.Add(friendList.Items[i].Value);
                }
            
                profileFbml = BuildProfileFbml(friends, greeting);

                if (createStoryCheckBox.Checked) {
                    FeedStory story = new FeedStory(HelloWorldStoryTemplate, fbApplication.Service.UserID, friends);
                    story.AddTemplateValue("greeting", greeting);

                    service.Feed.PublishMiniFeedStory(story);
                }
            }
        }
        else {
            profileFbml = BuildProfileFbml(null, greeting);
        }

        UserPreferences preferencecs = new UserPreferences();
        preferencecs[0] = greetingDropDownList.SelectedItem.Value;

        service.Preferences.SavePreferences(preferencecs);

        if (profileFbml != null) {
            service.Profile.SetFbml(profileFbml, service.UserID);
            fbApplication.Redirect(this, service.ProfileUrl);
        }
    }
    
    private static readonly FeedStoryTemplate HelloWorldStoryTemplate =
        new FeedStoryTemplate("<fb:name uid=\"{actor}\" useyou=\"false\"/> said <a href=\"http://apps.facebook.com/nikhilrandom\">Hello World</a>.",
                              "{greeting} {target}");
  </script>
</body>
</html>
